<template>
  <div class="userorder">
    <h3>我的订单</h3>
    <el-divider></el-divider>

    <el-collapse accordion>
      <el-collapse-item>
        <template slot="title">
          <div class="title" style="display: flex;justify-content: space-between;width: 100%;font-size: 18px">
            <span>群龄成长计划<i class="el-icon-s-marketing"></i></span>
            <span style="margin-right: 10px;font-size: 12px">当前群龄{{ qunling<=0?'0天':qunling }}</span>
          </div>
        </template>
        <h3 style="color: #3F4254;margin: 10px 0 0 ;font-size: 17px">折扣计划</h3>
        <el-table
            :data="plan"
            style="width: 100%">
          <el-table-column
              prop="age"
              label="群龄">
          </el-table-column>
          <el-table-column
              prop="zhe"
              label="折扣">
          </el-table-column>
          <el-table-column
              label="领取">
            <template slot-scope="scope">
              <div :style="{'background': 'url('+((userlv-2)>=scope.$index?yes:no)+') 0 0/contain no-repeat','width': '23px','height': '23px'}"></div>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <van-empty description="暂时订单" v-if="userorderArr?!userorderArr.length:true" />
    <el-card class="box-card" v-for="(v,i) in sciktArr" style="margin: 20px 0">

      <div slot="header" class="clearfix">
        <span style="line-height: 32px;font-size: 22px">{{ v.name }}</span>
        <el-tag style="float: right;" :type="v.zt==='0'?'':v.zt==='1'?'success':'danger'">{{ v.zt==='0'?'未付款':v.zt==='1'?'生效中':'已过期' }}</el-tag>
      </div>

      <el-timeline >
        <el-timeline-item v-for="timeitem in v.timeArr"
          :type="timeitem.type"
          :timestamp="timeitem.time">
        {{ timeitem.name }}<el-tag style="margin-left: 5px" size="mini" effect="dark" v-if="timeitem.tip">{{timeitem.tip}}</el-tag>
        </el-timeline-item>
      </el-timeline>
      <el-row type="flex" justify="end" style="color: #909399" :style="{'margin-bottom':v.zt==='1'?'20px':0}">
        <small>订单号：{{v.ddh}}
          <el-tooltip class="item" effect="dark" :content="tipMsg" v-model="v.copy_flag" :manual="true" placement="top">
            <i @click="copy(v,i)" :class="v.copy_class"></i>
          </el-tooltip>
        </small>
      </el-row>
      <el-row type="flex" justify="center">
        <el-button plain type="primary" v-if="v.zt==='1'" @click="xufei(v)">续费</el-button>
      </el-row>
    </el-card>

    <el-drawer
        title="续费面板"
        size="50%"
        :visible.sync="drawer"
        direction="btt"
        >
      <div style="margin: 0 20px 10px;display: flex;flex-direction: column;justify-content: space-between;min-height: 90%;">
        <el-row>
          <el-col :lg="7" :md="11" style="margin-right: 20px;margin-top: 10px" v-for="v in taocan">
            <el-card class="box-card">
              <el-radio v-model="radio" :label="v.id">
                <span v-html="v.Introduce" style="line-height: 30px;"></span><el-tag size="mini">{{ v.tag }}</el-tag>
              </el-radio>
            </el-card>
          </el-col>
          <div class="fill hidden-sm-and-up" style="width: 100%;height: 60px;float: left"></div>
<!--          <el-col :lg="7" :md="11" style="margin-right: 20px;margin-top: 10px">
            <el-card class="box-card">
              <el-radio disabled v-model="radio" label="内部群 20/月" @change="radio_change('20')">
                20/月<br><br>
                包含一个<el-link type="warning">内部群</el-link>、大群 <el-tag size="mini">实惠</el-tag>
              </el-radio>
            </el-card>
          </el-col>

          <el-col :lg="7" :md="11" style="margin-right: 20px;margin-top: 10px">
            <el-card class="box-card">
              <el-radio v-model="radio"  label="群主群 50/月" >
                50/月<br><br>
                包含一个群主群、大群 <el-tag size="mini">体验</el-tag>
              </el-radio>
            </el-card>
          </el-col>

          <el-col :lg="7" :md="11" style="margin-right: 20px;margin-top: 10px">
            <el-card class="box-card">
              <el-radio v-model="radio"  label="群主群 120/季" >
                120/季<br><br>
                包含一个群主群、大群 <el-tag size="mini">老铁</el-tag>
              </el-radio>
            </el-card>
          </el-col>

          <el-col :lg="7" :md="11" style="margin-right: 20px;margin-top: 10px">
            <el-card class="box-card">
              <el-radio v-model="radio"  label="群主群 300/年" >
                300/年<br><br>
                包含一个群主群、大群 <el-tag size="mini">推荐</el-tag>
              </el-radio>
            </el-card>
          </el-col>-->

        </el-row>
        <el-row type="flex" justify="center">
          <el-button type="primary" class="hidden-xs-only" style="margin-top: 10px" @click="zf()" :loading="menbanbtnloading">确定支付</el-button>
          <el-button type="primary" class="hidden-sm-and-up" style="margin: 10px 0 0 0 ;position: fixed;bottom: 10px;left: 50%;transform: translate(-50%)" @click="zf()" :loading="menbanbtnloading">确定支付</el-button>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import qs from "qs";
import yes from '../../assets/orderyes.png'
import no from '../../assets/orderno.png'
import {getOrderInfo, getTaocan, setOrder, setOrderXufei} from "../../utils/api";
import utils from "@/utils/time";
import {mapState} from "vuex";
/*计算两个月相差的月数*/
const monthNumber=(bigDate, smallDate)=>{
  let obj = {
    m:0,d:0
  }
  const dateOne = new Date(bigDate-0);
  const dateTwo = new Date(smallDate-0);

  const yearOne = dateOne.getFullYear();
  const monthOne = dateOne.getMonth() + 1;
  const dayOne = dateOne.getDate()
  const yearTwo = dateTwo.getFullYear();
  const monthTwo = dateTwo.getMonth() + 1;
  const dayTwo = dateTwo.getDate()

  // 两个日期的月份数
  const oneMonthNum = yearOne * 12 + monthOne;
  const twoMonthNum = yearTwo * 12 + monthTwo;
  obj.m= Math.abs(oneMonthNum - twoMonthNum)-0;
  // if(dayTwo>)
  if(dayTwo>dayOne){
    //8.11 7.28 默认31天 11+（31-28）
    obj.m--;
    obj.d = (31-(dayTwo-0))+dayOne
  }else{
    //8.28  7.21  28-21=7
    obj.d = dayOne-dayTwo
  }
  return obj
}
export default {
  name: "UserOrder",
  data() {
    return {
      yes,no,
      userorderArr:[],
      drawer: false,
      dangeorder:{},
      radio:'',
      menbanbtnloading:false,
      sciktArr:[],
      xufeiArr:[],
      qunling:0,
      taocan:null,
      plan:[
        {
          age:'3个月',
          zhe:'0.9',
          zt:'0'
        },{
          age:'6个月',
          zhe:'0.8',
          zt:'0'
        },{
          age:'9个月',
          zhe:'0.7',
          zt:'0'
        },{
          age:'12个月',
          zhe:'0.6',
          zt:'0'
        },{
          age:'18个月',
          zhe:'0.5',
          zt:'0'
        },{
          age:'24个月',
          zhe:'0.3',
          zt:'0'
        }
      ],
      tipMsg:'复制成功'
    };
  },
  created() {
    getOrderInfo().then(respose=>{
      this.userorderArr=respose.body;
      let now = new Date().getTime();
      if(this.userorderArr){
        this.userorderArr.forEach(v=>{
          if(v.cz==="0"){
            v.copy_class='el-icon-copy-document'
            v.copy_flag = false
            this.sciktArr.unshift(v);
          }else if(v.cz==="1"){
            this.xufeiArr.unshift(v);
          }
        })
        /*处理首次订单*/
        this.sciktArr.forEach((v=>{
          if(v.zt==="0"){
            if(v.cjsj>(now+60*30)){
              v.zt="2";
              v.dqsj=utils.timestampToTime(v.dqsj,5);
              v.cjsj=utils.timestampToTime(v.cjsj,5);
              v.timeArr=[{type:"primary",time:v.cjsj,name:"创建时间"},{type:"success",time:"",name:"使用中"},{type:"danger",time:v.dqsj,name:"到期时间"}]
              setOrder(qs.stringify({ddh:v.ddh})).then(()=>{}).catch(()=>{})
            }else{
              v.dqsj=utils.timestampToTime(v.dqsj,5);
              v.cjsj=utils.timestampToTime(v.cjsj,5);
              this.$set(v,"timeArr",[{type:"primary",time:v.cjsj,name:"创建时间"},{type:"",time:"",name:"使用中"},{type:"",time:v.dqsj,name:"到期时间"}])
            }
          }else if(v.zt==="1"){
            if(v.dqsj<now){
              v.zt="2";
              v.dqsj=utils.timestampToTime(v.dqsj,5);
              v.cjsj=utils.timestampToTime(v.cjsj,5);
              this.$set(v,"timeArr",[{type:"primary",time:v.cjsj,name:"创建时间"},{type:"success",time:"",name:"使用中"},{type:"danger",time:v.dqsj,name:"到期时间"}])
              setOrder(qs.stringify({ddh:v.ddh})).then(()=>{}).catch(()=>{})
            }else {
              v.lv = monthNumber(new Date().getTime(),v.cjsj)
              if(v.lv.m>=1){
                //超过一个月
                this.qunling = `${ v.lv.m }个月${v.lv.d==0?'':v.lv.d+'天'}`
              }else{
                this.qunling = `${v.lv.d}天`
              }
              v.dqsj=utils.timestampToTime(v.dqsj,5);
              v.cjsj=utils.timestampToTime(v.cjsj,5);
              this.$set(v,"timeArr",[{type:"primary",time:v.cjsj,name:"创建时间"},{type:"success",time:"",name:"使用中"},{type:"",time:v.dqsj,name:"到期时间"}])
            }
          }else if(v.zt==="2"){
            v.dqsj=utils.timestampToTime(v.dqsj,5);
            v.cjsj=utils.timestampToTime(v.cjsj,5);
            this.$set(v,"timeArr",[{type:"primary",time:v.cjsj,name:"创建时间"},{type:"success",time:"",name:"使用中"},{type:"danger",time:v.dqsj,name:"到期时间"}])
          }
        }))
        /*处理续费订单*/
        this.xufeiArr.forEach((v=>{
          /*找到续费与首次的订单 将续费订单里的创建时间记录 获得原首次的订单信息 将本次创建时间插入到首次订单的数组里*/
          let index = this.sciktArr.findIndex((item,i)=>{
            return item.ddh===v.fuddh
          })
          v.cjsj=utils.timestampToTime(v.cjsj,5);
          this.sciktArr[index].timeArr.splice(1, 0, {type:"success",time:v.cjsj,name:`续费`,tip:v.name});
        }))

        /*如果是开通就显示提示*/
        if(this.$route.query.tip){
          this.tipMsg = '请复制订单号发送给管理员进群'
          this.sciktArr[this.sciktArr.length-1].copy_flag = true
        }
      }

      //获得套餐信息
      getTaocan().then(res=>{
        this.taocan = res.body
        if(this.userlv>=2){
          this.taocan.forEach(v=>{
            let one = v.Introduce.split('<br>')
            let two = one[0].split('/')
            let tmp = (two[0]-0)*(this.plan[this.userlv-2].zhe-0)+'/'+two[1]
            v.Introduce = `<s>${one[0]}</s>&nbsp;&nbsp;${tmp}（群龄成长计划${(this.plan[this.userlv-2].zhe-0)*10}折）<br>${one[1]}`
          })
        }
      }).catch(err=>{
        console.log(err)
      })
    }).catch(error=>{
      console.log(error);
    })

  },
  methods:{
    xufei(v){
      this.drawer=true;
      this.dangeorder=v;
      this.radio=this.taocan[0].id
    },
    zf(){
      this.menbanbtnloading=true;
      setOrderXufei(qs.stringify({pid:this.radio,ddh:this.dangeorder.ddh})).then(respose=>{
        if(respose.status===200){
          this.$message({
            message: '续费成功',
            type: 'success'
          });
          let index = this.sciktArr.findIndex((item,i)=>{
            return item.ddh===this.dangeorder.ddh
          })
          let cjsj=utils.timestampToTime(new Date().getTime(),5);
          let dqsj1 = new Date(this.dangeorder.dqsj.replace(/-/g, '/')).getTime();
          dqsj1+=(this.taocan.filter(v=>v.id==this.radio)[0].time-0);
          let dqsj = utils.timestampToTime(dqsj1,5)
          //dqsj1计算后 更新this.dangeorder中dqsj
          this.dangeorder.dqsj = dqsj
          this.sciktArr[index].timeArr.splice(this.sciktArr[index].timeArr.length-2, 0, {type:"success",time:cjsj,name:"续费",tip:this.taocan.filter(v=>v.id==this.radio)[0].name});
          this.sciktArr[index].timeArr.splice(-1, 1, {type:"",time:dqsj,name:"到期时间"});
          this.drawer=false
          this.menbanbtnloading=false;
        }else{
          this.$message({
            message: respose.msg,
            type: 'error'
          });
          this.drawer=false
          this.menbanbtnloading=false;
        }
      }).catch(error=>{
        console.log(error);
      })
    },
    copy(v,i){
      if(v.copy_class=='el-icon-circle-check') return
      if(this.$route.query.tip){
        v.copy_flag = false
      }
      let copyInput = document.createElement('input');//创建input元素
      document.body.appendChild(copyInput);//向页面底部追加输入框
      copyInput.setAttribute('value', v.ddh);//添加属性，将url赋值给input元素的value属性
      copyInput.select();//选择input元素
      document.execCommand("Copy");//执行复制命令
      if(this.$route.query.tip){
        setTimeout(()=>{
          v.copy_class = 'el-icon-circle-check'
          this.tipMsg = '复制成功'
          v.copy_flag = true
        },300)
      }else{
        v.copy_class = 'el-icon-circle-check'
        v.copy_flag = true
      }
      this.sciktArr.splice(i,1,v)
      setTimeout(()=>{
        v.copy_flag = false
        this.sciktArr.splice(i,1,v)
      },3000)

      //复制之后再删除元素，否则无法成功赋值
      copyInput.remove();//删除动态创建的节点
    }
  },
  computed: {
    ...mapState([
      "userlv"
    ])
  },
}
</script>

<style scoped>
.el-drawer__header,#el-drawer__title{
  margin-bottom: 10px;
}
.el-radio{
  white-space: normal;
}
</style>
